package com.pb.infra.auth.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pb.infra.auth.entity.custom.PriviInterCustom;
import com.pb.infra.auth.mapper.CommonMapper;
import com.pb.infra.oth.exception.AppAuthException;
import com.pb.infra.oth.exception.ErrorCode;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.infra.auth.entity.pbsys.*;
import com.pb.infra.auth.mapper.custom.PriviMenuInterCustomMapper;
import com.pb.infra.auth.mapper.pbsys.PriviMenuInterfaceMapper;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.entity.common.Tree;
import com.pb.infra.auth.entity.custom.PriviMenuCustom;
import com.pb.infra.auth.mapper.custom.PriviMenuCustomMapper;
import com.pb.infra.auth.mapper.pbsys.PriviMenuMapper;
import com.pb.infra.auth.mapper.pbsys.PriviRoleMenuMapper;
import com.pb.infra.oth.util.Constant;
import com.pb.infra.oth.util.DateTimeUtil;
import com.pb.infra.oth.util.StringUtil;
import com.pb.infra.oth.util.UserInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 菜单管理
 *
 * @author liudebao
 * @date 2020/1/1
 */
@Service
public class PriviMenuService {

    /**
     * 菜单多表DAO映射
     */
    @Resource
    private PriviMenuCustomMapper priviMenuCustomMapper;

    /**
     * 菜单单表DAO映射
     */
    @Resource
    private PriviMenuMapper priviMenuMapper;

    /**
     * 角色菜单表DAO映射
     */
    @Resource
    private PriviRoleMenuMapper priviRoleMenuMapper;

    /**
     * 菜单接口多表DAO映射
     */
    @Resource
    private PriviMenuInterCustomMapper priviMenuInterCustomMapper;

    /**
     * 菜单接口单表DAO映射
     */
    @Resource
    private PriviMenuInterfaceMapper priviMenuInterfaceMapper;

    /**
     * redis数据访问
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    @Resource
    private CommonMapper commonMapper;

    /**
     * 读取全量菜单信息
     *
     * @return List<Tree> 全量菜单信息
     */
    public List<Tree> select(String appId) {
        return priviMenuCustomMapper.getMenus(appId);
    }

    /**
     * 读取某个菜单信息
     *
     * @param priviMenu 某个菜单代码
     * @return List<Map < String, Object>> 某个菜单信息
     */
    public Map<String, Object> getMenuById(PriviMenuCustom priviMenu) {
        List<Map<String, Object>> list = priviMenuCustomMapper.getMenuById(priviMenu);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 新建菜单
     *
     * @param priviMenu 请求参数
     */
    @Transactional
    public Result insert(PriviMenuCustom priviMenu, HttpServletRequest request) {
        PriviMenuExample priviMenuExample = new PriviMenuExample();
        PriviMenuExample.Criteria criteria = priviMenuExample.createCriteria();
        criteria.andAppIdEqualTo(priviMenu.getAppId());
        criteria.andEnNameEqualTo(priviMenu.getMenuName());
        List<PriviMenu> list = priviMenuMapper.selectByExample(priviMenuExample);
        if (list != null && list.size() > 0) {
            throw new AppAuthException(ErrorCode.ErrorCodeEnum.REPEAT_ENNAME);
        }
        // 构造菜单编号、顺序号
        String token = request.getHeader(jwtTokenConfig.getHeader());
        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
        PriviMenu priviMenu1 = new PriviMenu();
        priviMenu1.setSerialNo(new BigDecimal(priviMenuCustomMapper.getMaxSeqId()));
        String menuId = String.valueOf(priviMenuCustomMapper.getMaxMenuId());
        priviMenu1.setMenuId(menuId);
        if ("0".equals(priviMenu.getMenuType())) {
            priviMenu.setMenuPath("/" + priviMenu1.getMenuId());
        }
        if (Constant.OK.equals(priviMenu.getParentId()) && priviMenu.getMenuPath() != null && priviMenu.getMenuPath().isEmpty() && priviMenu.getMenuPath().startsWith("/")) {
            priviMenu1.setMenuPath("/" + priviMenu.getMenuPath());
        } else {
            priviMenu1.setMenuPath(priviMenu.getMenuPath());
        }
        priviMenu1.setCreateUser(userInfo.getUserId());
        priviMenu1.setUpdateUser(userInfo.getUserId());
        priviMenu1.setUpperId(priviMenu.getParentId());
        priviMenu1.setHideFlag(priviMenu.getHideFlag());
        priviMenu1.setCatalogFlag(priviMenu.getMenuType());
        priviMenu1.setCnName(priviMenu.getMenuTitle());
        priviMenu1.setEnName(priviMenu.getMenuName());
        priviMenu1.setComponent(priviMenu.getComponent());
        priviMenu1.setFromType(priviMenu.getSrcType());
        priviMenu1.setHref(priviMenu.getHref());
        priviMenu1.setLevelId(new BigDecimal(priviMenu.getLvl()));
        if (!StringUtil.isEmpty(priviMenu.getIcon())) {
            priviMenu1.setMenuIcon(priviMenu.getIcon());
        } else {
            priviMenu1.setMenuIcon("");
        }
        priviMenu1.setSysFlag(priviMenu.getSysFlag());
        priviMenu1.setCreateTime(DateTimeUtil.getStrFromNewDate());
        priviMenu1.setUpdateTime(DateTimeUtil.getStrFromNewDate());
        priviMenu1.setAppId(priviMenu.getAppId());
        priviMenuMapper.insertSelective(priviMenu1);
        return Result.ok(priviMenu1);
    }

    /**
     * 修改菜单
     *
     * @param priviMenu 请求参数
     */
    @Transactional
    public void update(PriviMenuCustom priviMenu, HttpServletRequest request) {
        // 构造菜单编号、顺序号
        String token = request.getHeader(jwtTokenConfig.getHeader());
        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
        if (Constant.OK.equals(priviMenu.getUpperId()) && priviMenu.getMenuPath() != null && priviMenu.getMenuPath().isEmpty() && priviMenu.getMenuPath().startsWith("/")) {
            priviMenu.setMenuPath("/" + priviMenu.getMenuPath());
        }
        priviMenu.setUpdateUser(userInfo.getUserId());

        PriviMenu priviMenu1 = new PriviMenu();
        if (Constant.OK.equals(priviMenu.getParentId()) && priviMenu.getMenuPath() != null && priviMenu.getMenuPath().isEmpty() && priviMenu.getMenuPath().startsWith("/")) {
            priviMenu1.setMenuPath("/" + priviMenu.getMenuPath());
        } else {
            priviMenu1.setMenuPath(priviMenu.getMenuPath());
        }
        priviMenu1.setMenuId(priviMenu.getMenuId());
        priviMenu1.setUpdateUser(userInfo.getUserId());
        priviMenu1.setUpperId(priviMenu.getParentId());
        priviMenu1.setHideFlag(priviMenu.getHideFlag());
        priviMenu1.setCatalogFlag(priviMenu.getMenuType());
        priviMenu1.setCnName(priviMenu.getMenuTitle());
        priviMenu1.setEnName(priviMenu.getMenuName());
        priviMenu1.setComponent(priviMenu.getComponent());
        priviMenu1.setFromType(priviMenu.getSrcType());
        priviMenu1.setHref(priviMenu.getHref());
        priviMenu1.setLevelId(new BigDecimal(priviMenu.getLvl()));
        if (!StringUtil.isEmpty(priviMenu.getIcon())) {
            priviMenu1.setMenuIcon(priviMenu.getIcon());
        }
        priviMenu1.setSysFlag(priviMenu.getSysFlag());
        priviMenu1.setUpdateTime(DateTimeUtil.getStrFromNewDate());
        priviMenuMapper.updateByPrimaryKeySelective(priviMenu1);
    }

    /**
     * 删除菜单
     *
     * @param paramMap 请求参数
     */
    @Transactional
    public void delete(Map<String, Object> paramMap) {
        // 删除所有涉及的菜单节点、权限信息
        // 前端已经组织过目标节点的所有下属节点
        for (String menuId : (List<String>) paramMap.get("menuIds")) {
            PriviRoleMenuExample priviRoleMenuExample = new PriviRoleMenuExample();
            PriviRoleMenuExample.Criteria criteria = priviRoleMenuExample.createCriteria();
            criteria.andMenuIdEqualTo(menuId);
            priviRoleMenuMapper.deleteByExample(priviRoleMenuExample);
            priviMenuCustomMapper.delCorpMenu(menuId);
            priviMenuCustomMapper.delMenuInter(menuId);
            priviMenuMapper.deleteByPrimaryKey(menuId);
        }
    }

    /**
     * 查询菜单对应接口
     * @param paramMap
     * @param page
     * @return
     */
    public Result getMenuInters(Map<String, Object> paramMap, Page page) {
        if (page != null && page.getPageIndex() != null && page.getPageSize() != null) {
            PageHelper.startPage(page.getPageIndex(), page.getPageSize());
        }
        List<Map<String, Object>> list = priviMenuInterCustomMapper.getMenuInters(paramMap);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 新增菜单接口
     * @param priviMenuInterface
     * @param request
     */
    @Transactional
    public void insertInter(PriviMenuInterface priviMenuInterface, HttpServletRequest request) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
        Map<String, Object> map = new HashMap<>();
        map.put("menuId", priviMenuInterface.getMenuId());
        map.put("interfaceId", priviMenuInterface.getInterfaceId());
        map.put("userId", userInfo.getUserId());
        map.put("time", DateTimeUtil.getDate());
        priviMenuInterCustomMapper.addInterData(map);
        userInfo.setMenuFlag("1");
        //redisTemplate.opsForValue().set(token + "menuFlag", "1", 24L, TimeUnit.HOURS);
        List<Map<String, Object>> list = priviMenuInterCustomMapper.queryMenuRole(map);
        for (int i = 0; i < list.size(); i++) {
            if (!StringUtil.isEmpty(list.get(i).get("roleId"))) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("roleId", list.get(i).get("roleId").toString());
                map1.put("resId", priviMenuInterface.getInterfaceId());
                map1.put("userId", userInfo.getUserId());
                map1.put("time", DateTimeUtil.getDate());
                priviMenuInterCustomMapper.delRoleRes(map1);
                priviMenuInterCustomMapper.addRoleRes(map1);
            }
        }
        if (list != null && list.size() > 0) {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("positionId", userInfo.getPositionId());
            map2.put("list", list);
            List<Map<String, Object>> list1 = priviMenuInterCustomMapper.selPosRole(map2);
            if (list1 != null && list1.size() > 0) {
                map2.put("userId", userInfo.getUserId());
                List<PriviInterCustom> list2 = priviMenuInterCustomMapper.selRoleMenuByUserPosId(map2);
                userInfo.setPositionMenus(list2);
                userInfo.setMenuFlag("0");
                //redisTemplate.opsForValue().set(token + "positionMenus", list2, 24L, TimeUnit.HOURS);
                //redisTemplate.opsForValue().set(token + "menuFlag", "0", 24L, TimeUnit.HOURS);
            }
        }
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("userId", userInfo.getUserId());
        List<PriviInterCustom> allInters = commonMapper.selAllInterByUserId(userMap);
        userInfo.setAllInters(allInters);
        userInfo.setAllIntersFlag("1");
        if (redisTemplate.hasKey(token)) {
            redisTemplate.delete(token);
        }
        redisTemplate.opsForValue().set(token, userInfo, 24L, TimeUnit.HOURS);
        //redisTemplate.opsForValue().set(token + "allInters", allInters, 24L, TimeUnit.HOURS);
    }

    /**
     * 修改菜单接口
     * @param priviMenuInterface
     */
    @Transactional
    public void updateInter(PriviMenuInterface priviMenuInterface) {
        PriviMenuInterfaceExample priviMenuInterfaceExample = new PriviMenuInterfaceExample();
        PriviMenuInterfaceExample.Criteria criteria = priviMenuInterfaceExample.createCriteria();
        criteria.andMenuIdEqualTo(priviMenuInterface.getMenuId());
        criteria.andInterfaceIdEqualTo(priviMenuInterface.getInterfaceId());
        priviMenuInterfaceMapper.updateByExampleSelective(priviMenuInterface,priviMenuInterfaceExample);
    }

    /**
     * 删除菜单接口
     * @param paramMap
     */
    @Transactional
    public void deleteInter(List<Map<String, Object>> paramMap) {
        if (!StringUtil.isEmpty(paramMap)) {
            for (int i = 0; i < paramMap.size(); i++) {
                priviMenuInterCustomMapper.delInterData(paramMap.get(i));
            }
        }
    }

    /**
     * 修改菜单拖拽位置
     * @param paramMap
     */
    @Transactional
    public void updateMenuPath(Map<String, Object> paramMap) {
        try {
            if (StringUtil.isEmpty(paramMap.get("type"))) {
                throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_PARAMS_ERROR);
            }
            String type = paramMap.get("type").toString();
            if ("0".equals(type)) {
                int maxSerial = priviMenuCustomMapper.getMaxSeqId();
                PriviMenu priviMenu = new PriviMenu();
                priviMenu.setMenuId(paramMap.get("id").toString());
                priviMenu.setLevelId(new BigDecimal(Integer.parseInt(paramMap.get("parentLvl").toString()) + 1));
                priviMenu.setSerialNo(new BigDecimal(maxSerial));
                priviMenu.setUpperId(paramMap.get("parentId").toString());
                priviMenuMapper.updateByPrimaryKeySelective(priviMenu);
            } else if ("1".equals(type)) {
                String seq = paramMap.get("seq").toString();
                int maxSerial = priviMenuCustomMapper.getMaxSeqId();
                PriviMenu priviMenu = new PriviMenu();
                priviMenu.setMenuId(paramMap.get("id").toString());
                priviMenu.setLevelId(new BigDecimal(paramMap.get("parentLvl").toString()));
                priviMenu.setSerialNo(new BigDecimal(maxSerial));
                priviMenu.setUpperId(paramMap.get("parentId").toString());
                priviMenuMapper.updateByPrimaryKeySelective(priviMenu);
                PriviMenuExample priviMenuExample = new PriviMenuExample();
                PriviMenuExample.Criteria criteria = priviMenuExample.createCriteria();
                criteria.andUpperIdEqualTo(paramMap.get("parentId").toString());
                criteria.andSerialNoGreaterThanOrEqualTo(new BigDecimal(seq));
                criteria.andSerialNoNotEqualTo(new BigDecimal(maxSerial));
                priviMenuExample.setOrderByClause("SERIAL_NO");
                List<PriviMenu> list = priviMenuMapper.selectByExample(priviMenuExample);
                for (int i = 0; i < list.size(); i++) {
                    PriviMenu priviMenu1 = list.get(i);
                    priviMenu1.setSerialNo(new BigDecimal(maxSerial + 1));
                    priviMenuMapper.updateByPrimaryKeySelective(priviMenu1);
                    maxSerial += 1;
                }
            } else if ("2".equals(type)) {
                String seq = paramMap.get("seq").toString();
                int maxSerial = priviMenuCustomMapper.getMaxSeqId();

                PriviMenuExample priviMenuExample = new PriviMenuExample();
                PriviMenuExample.Criteria criteria = priviMenuExample.createCriteria();
                criteria.andUpperIdEqualTo(paramMap.get("parentId").toString());
                criteria.andSerialNoLessThanOrEqualTo(new BigDecimal(seq));
                criteria.andMenuIdNotEqualTo(paramMap.get("id").toString());
                priviMenuExample.setOrderByClause("SERIAL_NO");
                List<PriviMenu> list1 = priviMenuMapper.selectByExample(priviMenuExample);

                PriviMenuExample priviMenuExample2 = new PriviMenuExample();
                PriviMenuExample.Criteria criteria2 = priviMenuExample2.createCriteria();
                criteria2.andUpperIdEqualTo(paramMap.get("parentId").toString());
                criteria2.andSerialNoGreaterThan(new BigDecimal(seq));
                criteria2.andMenuIdNotEqualTo(paramMap.get("id").toString());
                priviMenuExample2.setOrderByClause("SERIAL_NO");
                List<PriviMenu> list = priviMenuMapper.selectByExample(priviMenuExample2);

                for (int i = 0; i < list1.size(); i++) {
                    PriviMenu priviMenu1 = list1.get(i);
                    priviMenu1.setSerialNo(new BigDecimal(maxSerial));
                    priviMenuMapper.updateByPrimaryKeySelective(priviMenu1);
                    maxSerial += 1;
                }

                PriviMenu priviMenu = new PriviMenu();
                priviMenu.setMenuId(paramMap.get("id").toString());
                priviMenu.setLevelId(new BigDecimal(paramMap.get("parentLvl").toString()));
                priviMenu.setSerialNo(new BigDecimal(maxSerial));
                priviMenu.setUpperId(paramMap.get("parentId").toString());
                priviMenuMapper.updateByPrimaryKeySelective(priviMenu);
                maxSerial += 1;
                for (int i = 0; i < list.size(); i++) {
                    PriviMenu priviMenu1 = list.get(i);
                    priviMenu1.setSerialNo(new BigDecimal(maxSerial));
                    priviMenuMapper.updateByPrimaryKeySelective(priviMenu1);
                    maxSerial += 1;
                }
            }
        } catch (AppAuthException e) {
            e.printStackTrace();
        }
    }

    public Result queryAllInter() {
        List<Map<String, Object>> list = priviMenuInterCustomMapper.queryAllInter();
        return Result.ok(list);
    }

}
